package linearList;

public class TwoWayLinkList<T> {
    private Node head;
    private Node last;
    private int N;

    public TwoWayLinkList() {
        this.head = new Node(null, null, null);
        this.last = null;
        this.N = 0;
    }

    /*
    .public void clear()：空置线性表
2.publicboolean isEmpty()：判断线性表是否为空，是返回true，否返回false
3.public int length():获取线性表中元素的个数

     */
    //空置线性表
    public void clear() {
        this.N = 0;
        head.item = null;
        head.next = null;
        head.pre = null;
    }

    //判断线性表是否为空
    public boolean isEmpty() {
        return N == 0;
    }

    //获取线性表中的元素的个数
    public int length() {
        return N;
    }

    public void insert(T t) {
        if (last==null) {
            Node newNode = new Node(t, null, head);
            last = newNode;
            head.next = last;
        } else {
            Node nodelast = last;
            Node newNode = new Node(t, null, nodelast);
            nodelast.next = newNode;
            last = newNode;
        }
        N++;
    }
    public void insert(int i , T t){
        if (i <0 || i >=N){
            throw new RuntimeException("索引越界");
        }
        Node pre = head;
        for (int index = 0 ; index < i ; index++ ){
            pre =pre.next;
        }
        Node curr = pre.next;
        Node newNode = new Node(t, curr, pre);
        curr.pre=newNode;
        pre.next = newNode;
        N++;
    }
    public T remove(int i){
        if (i <0 || i >=N){
            throw new RuntimeException("索引越界");
        }
        Node pre = head;
        for (int index = 0 ; index < i ; index++ ){
            pre =pre.next;
        }
        Node curr = pre.next;
        Node last = curr.next;
        last.pre = pre;
        pre.next = last;
        N--;
        return curr.item;
    }
    public int indexOf(T t){
        Node tem = head;
        for (int i = 0 ; tem.item != null; i++){
            tem=tem.next;
            if (tem.item.equals(t)){
                return i;
            }
        }
        return -1;
    }
    //节点类
    public class Node {
        T item;
        Node next;
        Node pre;

        public Node(T item, Node next, Node pre) {
            this.item = item;
            this.next = next;
            this.pre = pre;
        }
    }
}
